import operate from '@dfeidao/atom-nodejs/db/operate';
import query from '@dfeidao/atom-nodejs/db/query';
import uuid from 'uuid';
interface Message {
	role_type_id: string;
	role_allot_id: string;
	productid: string;
	group_id: string;
	connector: string;
	field: string;
	operate: string;
	field_value: string;
	fieldtype: string;
}

interface Data {
	group_id: string;
	tablename: string;
	systemid: string;
	priority: number;
	_id: string;
}
export default async function atom(msg: Message, action_id: string, session_id: string) {
	const systemid = '12';
	const { exec, insert } = operate(action_id, session_id, systemid);
	const { exec: e, prepare: p } = query(action_id, session_id, systemid);
	// const { exec: c, prepare: u } = update(action_id, session_id, spaceid, systemid);

	const productid = msg.productid;
	const role_allot_id = msg.role_allot_id;
	const group_id = msg.group_id;
	// console.log(msg)
	p('pub_role_type', ['tablename', 'systemid'], { productid, _id: msg.role_type_id }, 199, 1, [], []);
	const [data1] = await e<Data>();
	// console.log(data1)
	p('allot_conditions_group', ['group_id'], { $or: [{ productid, role_allot_id, group_id }, { productid, role_allot_id, parent_group_id: group_id }] }, 199, 1, [], []);
	const [data] = await e<Data>();
	// console.log(data)
	const arr = data.map((v) => {
		return v.group_id;
	});
	// console.log(arr);
	p('allot_conditions', ['_id', 'connector', 'group_id', 'field', 'operate', 'field_value', 'priority'], { productid, group_id: { $in: arr } }, 199, 1, ['priority'], []);
	const [data2] = await e<Data>();
	// console.log(data2)
	// const arr1 = data2.map((v) => {
	// 	const obj = {
	// 		_id: v._id, connector: msg.connector
	// 	};
	// 	return obj;
	// });
	// arr1.forEach((v) => {
	// 	update('allot_conditions', { _id: v._id }, { connector: msg.connector });

	// });

	let priority = 0;
	if (data2.length) {
		priority = data2[data2.length - 1].priority + 1;
	}
	insert('allot_conditions', {
		_id: uuid(),
		productid,
		connector: msg.connector,
		group_id,
		field: msg.field,
		operate: msg.operate,
		field_value: msg.field_value,
		fieldtype: msg.fieldtype,
		tablename: data1[0].tablename,
		systemid: data1[0].systemid,
		priority
	});
	const res = await exec();
	if (res.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}

}

